package com.qhgrain.app.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.service.ApplicationService;
import com.qhgrain.app.service.MyapplicationService;
import com.qhgrain.app.service.UserService;
import com.qhgrain.app.vo.MyAppVo;
import com.qhgrain.app.vo.PairVo;
import com.qhgrain.app.vo.UserVo;

@Controller
@RequestMapping("/myapp")
public class MyApplicationController {

	private static Logger LOG = LoggerFactory.getLogger(MyApplicationController.class);
	
	@Autowired
	private MyapplicationService myapplicationService;
	
	@Autowired
	private UserService userService;
	@Autowired
	private ApplicationService applicationService;
	
	@RequestMapping(value="/list" )
	public String pageList() throws Exception{
		
		return "myapp/myapp_list";
	}
	
	@RequestMapping(value="/list/table")
	public String queryMyAppsForTable(Model model,String userName, String pageNo,String pageSize) throws Exception{
		
		int num = 1;
		int size = 10;
		if(StringUtil.isNotBlank(pageNo)){
			num = Integer.parseInt(pageNo);
		}
		if(StringUtil.isNotBlank(pageSize)){
			size = Integer.parseInt(pageSize);
		}
		if(StringUtil.isNotBlank(userName)){
			model.addAttribute("userName",userName);
		}
		PageBean<MyAppVo> page = this.myapplicationService.queryPage(null, userName, num, size);
		
		model.addAttribute("pageBean", page);
		return "myapp/myapp_list_table";
	}
	
	@RequestMapping(value="/edit/{id}")
	public String editPage(Model model,@PathVariable String id) throws IOException{
		MyAppVo vo = this.myapplicationService.get(id);
		model.addAttribute("bean",vo);
		return "myapp/myapp_edit";
	}
	
	@RequestMapping(value="/update/order")
	@ResponseBody
	public JSONObject updateShowOrder(Model model,String id,String showOrder){
		JSONObject result = new JSONObject();
		try {
			this.myapplicationService.update(id,Integer.parseInt(showOrder));
			result.put("code", "success");
		} catch (Exception e) {
			result.put("code", "fail");
		}
		return result;
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public JSONObject delete(Model model, String ids){
		JSONObject result = new JSONObject();
		try {
			this.myapplicationService.delete(Arrays.asList(ids.split(",")));
			result.put("code", "success");
		} catch (Exception e) {
			result.put("code", "fail");
		}
		return result;
	}
	
	@RequestMapping(value="/add")
	public String addPage(Model model){
		
		return "myapp/myapp_add";
	}
	
	@RequestMapping(value="/open/user/page")
	public String openUserPage(Model model){
		
		return "myapp/select_user_page";
	}
	
	@RequestMapping(value="/query/user/table")
	public String queryUser(Model model,String unitName,String userName,String pageNo,String pageSize) throws NumberFormatException, Exception{
		int size = StringUtil.isBlank(pageSize)? 10 : Integer.parseInt(pageSize);
		if(StringUtil.isBlank(pageNo)){
			pageNo = "1";
		}
		PageBean<UserVo> pageBean = this.userService.queryPage(userName, null,null, unitName,null, null, "1", Integer.parseInt(pageNo), size);
		model.addAttribute("pageBean",pageBean);
		return "myapp/user_table_radio";
	}
	
	@RequestMapping(value="/query/apps/{userId}")
	@ResponseBody
	public JSONObject queryApps(Model model,@PathVariable("userId") String userId){
		JSONObject result = new JSONObject();
		try {
			//用户已有的常用应用
			List<MyAppVo> list1 = this.myapplicationService.queryList(userId);
			//用户所在群组所拥有的所有应用
			List<PairVo> list2 = this.applicationService.getAll(userId);
			//用户还没选择的
			List<PairVo> list3 = deal(list1,list2);
			
			result.put("code", "success");
			result.put("ownList", list1);
			result.put("noOwnList", list3);
		} catch (Exception e) {
			result.put("code", "fail");
		}
		
		
		return result;
	}
	private List<PairVo> deal(List<MyAppVo> list1 ,List<PairVo> list2){
		List<PairVo> list3 = new ArrayList<PairVo>();
		if(list1 == null || list2 == null){
			return list2;
		}
		boolean isExits = false;
		for(PairVo p : list2){
			isExits = false;
			for(MyAppVo m : list1){
				if(p.getCode().equals(m.getAppId())){
					isExits = true;
					break;
				}
			}
			if(!isExits){
				list3.add(p);
			}
		}
		return list3;
	}
	@RequestMapping(value="/save")
	@ResponseBody
	public JSONObject save(Model model,String userId,String appIds){
		JSONObject result = new JSONObject();
		try {
			if(StringUtil.isBlank(userId)){
				result.put("code", "fail");
			}else{
				this.myapplicationService.addBatch(userId, true, Arrays.asList(appIds.split(",")));
				result.put("code", "success");
			}
			
		} catch (Exception e) {
			LOG.error("保存用户常用应用出错...",e);
			result.put("code", "fail");
		}
		
		return result;
	}
}
